package com.atguigu.day01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class Flink03_UnboundedStream_WordCount {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
//        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //获取可以在本地打开UI界面执行环境 ！！！！！！！！注意！打包上传到集群上的时候不要用这种执行环境否则会报错
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());

        env.setParallelism(1);

        //2.获取无界流数据
        DataStreamSource<String> streamSource = env.socketTextStream("hadoop102", 9999);

        //3.利用flatmap将数据按照空格切分
        SingleOutputStreamOperator<String> wordDStream = streamSource.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String value, Collector<String> out) throws Exception {
                String[] words = value.split(" ");

                for (String word : words) {
                    out.collect(word);
                }

            }
        })
                //在算子中设置并行度
//                .setParallelism(2)
                ;

        //4.使用Map将数据转为Tuple2元组
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordToOneDSteam = wordDStream.map(r -> Tuple2.of(r, 1)).returns(Types.TUPLE(Types.STRING,Types.INT));

        //5.使用keyby将相同单词的数据聚合到一块
        KeyedStream<Tuple2<String, Integer>, Tuple> keyedStream = wordToOneDSteam.keyBy(0);

        //6.累加计算
        SingleOutputStreamOperator<Tuple2<String, Integer>> result = keyedStream.sum(1);

        result.print();

        //7.执行
        env.execute();
    }
}
